// 简单的通知状态存储
type ToastType = "success" | "error" | "info" | "warning";

interface Toast {
  id: number;
  message: string;
  type: ToastType;
  duration?: number;
}

// 使用自增ID确保通知的唯一性
let nextId = 1;

// 通知监听器
type ToastListener = (toasts: Toast[]) => void;
const listeners: ToastListener[] = [];
let toasts: Toast[] = [];

// 添加通知
export function addToast(message: string, type: ToastType = "info", duration: number = 3000): number {
  const id = nextId++;
  toasts = [...toasts, { id, message, type, duration }];
  
  // 通知所有监听器
  notifyListeners();
  
  // 设置自动移除计时器
  setTimeout(() => {
    removeToast(id);
  }, duration + 300); // 额外300ms用于动画
  
  return id;
}

// 移除通知
export function removeToast(id: number): void {
  toasts = toasts.filter(toast => toast.id !== id);
  notifyListeners();
}

// 订阅通知变化
export function subscribeToasts(listener: ToastListener): () => void {
  listeners.push(listener);
  
  // 立即通知新监听器当前状态
  listener([...toasts]);
  
  // 返回取消订阅的函数
  return () => {
    const index = listeners.indexOf(listener);
    if (index !== -1) {
      listeners.splice(index, 1);
    }
  };
}

// 通知所有监听器
function notifyListeners(): void {
  listeners.forEach(listener => listener([...toasts]));
} 